package com.devinlee.distributedlock.web;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 订单控制器
 * <p>
 * Created by devinlee in 2021.11.01
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private Redisson redisson;

    @GetMapping("/setVal")
    public Map<String, Object> setVal(String key, String val) {
        stringRedisTemplate.opsForValue().set(key, val);

        return new HashMap<String, Object>() {{
            put("code", 200);
            put("msg", "success");
        }};
    }

    @GetMapping("/getVal")
    public Map<String, Object> getVal(String key) {
        return new HashMap<String, Object>() {{
            put("code", 200);
            put("msg", "success");
            put("data", stringRedisTemplate.opsForValue().get(key));
        }};
    }


    /**
     * 分布式高并发减库存实例
     *
     * @return
     */
    @GetMapping("/stock")
    public Map<String, Object> stock() {
        RLock lock = redisson.getLock("PRODUCTS_LOCK_001");//注意使用下划线！！
        try {
            lock.lock(30, TimeUnit.SECONDS);
            int stock = Integer.valueOf(stringRedisTemplate.opsForValue().get("products-stock-001"));
            int finalStock = stock;
            if (stock > 0) {
                stock--;
                stringRedisTemplate.opsForValue().set("products-stock-001", String.valueOf(stock));
                System.out.println("成功购买了编号[" + finalStock + "]商品！");
                return new HashMap<String, Object>() {{
                    put("code", 200);
                    put("msg", "成功购买了编号[" + finalStock + "]商品！");
                }};
            }
            System.out.println("商品已售罄！");
            return new HashMap<String, Object>() {{
                put("code", 501);
                put("msg", "商品已售罄！");
            }};
        } finally {
            lock.unlock();
        }
    }
}
